"use strict";

var websiteSuggestions, websiteUrl, suggestboxContainer, suggestbox, websiteExceptions = [], mouseoverSuggestbox = !1;

function websiteCheck(website, isRegex, id, isImport) {
    isRegex || (website = $.domainFromURL(website));
    if ("" === website) {
        isImport || window.alert("Please enter website first!");
        return !1;
    }
    for (var i = 0; i < websiteExceptions.length; i++) if (i !== id && website === websiteExceptions[i].website) {
        isImport || window.alert("This website is already in the list!");
        return !1;
    }
    var rez = {
        website: website
    };
    if (!isRegex) if (-1 === website.indexOf("*")) rez.type = "m"; else {
        rez.type = "w";
        var regex = website.replace(/(\.|\+|\?|\^|\$|\[|\]|\(|\)|\||\{|\}|\'|\#)/g, "\\$1");
        regex = regex.replace(/(\*)/g, ".$1");
        rez.regex = "^" + regex + "$";
    }
    return rez;
}

function listAdd(website, isRegex, isImport) {
    var rez = websiteCheck(website, isRegex, -1, isImport);
    if (!1 === rez) return !1;
    websiteExceptions.push(rez);
    return !0;
}

function websiteAdd() {
    if (listAdd(websiteUrl.value, $("websiteRegex").checked, !1)) {
        makeTable();
        mouseoverSuggestbox = !1;
        suggestboxHide();
        optionsChange();
    }
    websiteUrl.value = "";
    websiteUrl.focus();
}

function websiteEditStart(id) {
    var td = $("we_" + id);
    if (td) {
        $.empty(td);
        var ctrlinput = document.createElement("input");
        ctrlinput.type = "button";
        ctrlinput.className = "btns cmd cmd-edit-cancel";
        ctrlinput.title = "Cancel";
        ctrlinput.value = "Cancel";
        td.appendChild(ctrlinput);
        (ctrlinput = document.createElement("input")).type = "button";
        ctrlinput.className = "btns cmd cmd-edit-save";
        ctrlinput.title = "Save website";
        ctrlinput.value = "Save";
        td.appendChild(ctrlinput);
        (ctrlinput = document.createElement("input")).id = "website_url_edit_" + id;
        ctrlinput.type = "text";
        ctrlinput.className = "website_url_edit";
        ctrlinput.placeholder = "e.g. www.example.com";
        ctrlinput.title = "e.g. www.example.com";
        ctrlinput.value = websiteExceptions[id].website;
        ctrlinput.addEventListener("keydown", websiteEditKeydown, !1);
        td.appendChild(ctrlinput);
        ctrlinput.focus();
        var ctrldiv = document.createElement("div");
        ctrldiv.style.display = "none";
        td.appendChild(ctrldiv);
        (ctrlinput = document.createElement("input")).id = "website_regex_" + id;
        ctrlinput.type = "checkbox";
        ctrlinput.title = "Check this box if you wish to use RegEx";
        ctrlinput.checked = void 0 === websiteExceptions[id].type;
        ctrldiv.appendChild(ctrlinput);
        var ctrllabel = document.createElement("label");
        ctrllabel.setAttribute("for", "website_regex_" + id);
        ctrllabel.title = "Check this box if you wish to use RegEx";
        ctrllabel.textContent = "Use RegEx";
        ctrldiv.appendChild(ctrllabel);
    }
}

function websiteEditCancel(id) {
    var ctrltd = $("we_" + id);
    if ("m" === websiteExceptions[id].type) {
        $.empty(ctrltd);
        var ctrla = document.createElement("a");
        ctrla.href = "http://" + websiteExceptions[id].website;
        ctrla.title = "Visit website: " + websiteExceptions[id].website;
        ctrla.target = "_blank";
        ctrla.textContent = websiteExceptions[id].website;
        ctrltd.appendChild(ctrla);
    } else ctrltd.textContent = websiteExceptions[id].website;
}

function websiteEditSave(id) {
    var rez = websiteCheck($("website_url_edit_" + id).value, $("website_regex_" + id).checked, parseInt(id, 10), !1);
    if (!1 !== rez) {
        websiteExceptions[id] = rez;
        makeTable();
        websiteUrl.focus();
    } else $("website_url_edit_" + id).focus();
    optionsChange();
}

function websiteEditKeydown(event) {
    var key = event.which ? event.which : event.keyCode;
    27 === key ? websiteEditCancel(event.target.parentElement.parentElement.getAttribute("data-id")) : 13 === key && websiteEditSave(event.target.parentElement.parentElement.getAttribute("data-id"));
}

function websiteRemove(id) {
    websiteExceptions.splice(id, 1);
    makeTable();
    optionsChange();
}

function makeTable() {
    var ctrltr, ctrltd, ctrla, ctrlimg, elb = $("exception_list_body");
    $.empty(elb);
    for (var i = 0; i < websiteExceptions.length; i++) {
        (ctrltr = document.createElement("tr")).setAttribute("data-id", i);
        elb.appendChild(ctrltr);
        (ctrltd = document.createElement("td")).id = "we_" + i;
        ctrltd.className = "elb_td1";
        ctrltr.appendChild(ctrltd);
        if ("m" === websiteExceptions[i].type) {
            (ctrla = document.createElement("a")).href = "http://" + websiteExceptions[i].website;
            ctrla.title = "Visit website: " + websiteExceptions[i].website;
            ctrla.target = "_blank";
            ctrla.textContent = websiteExceptions[i].website;
            ctrltd.appendChild(ctrla);
        } else ctrltd.textContent = websiteExceptions[i].website;
        (ctrltd = document.createElement("td")).className = "elb_td2";
        ctrltr.appendChild(ctrltd);
        (ctrlimg = document.createElement("img")).src = "images/edit.png";
        ctrlimg.className = "cmd cmd-rule-edit";
        ctrlimg.title = "Edit website";
        ctrltd.appendChild(ctrlimg);
        (ctrlimg = document.createElement("img")).src = "images/delete.png";
        ctrlimg.className = "cmd cmd-rule-delete";
        ctrlimg.title = "Remove from the list";
        ctrltd.appendChild(ctrlimg);
    }
}

function exceptionListBodyClick(event) {
    var element = event.target, classes = element.classList;
    if (classes.contains("cmd")) {
        "INPUT" === element.tagName && (element.disabled = !0);
        for (var parent = element.parentElement; "TR" !== parent.tagName; ) parent = parent.parentElement;
        var id = parent.getAttribute("data-id");
        classes.contains("cmd-rule-edit") ? websiteEditStart(id) : classes.contains("cmd-edit-cancel") ? websiteEditCancel(id) : classes.contains("cmd-edit-save") ? websiteEditSave(id) : classes.contains("cmd-rule-delete") && websiteRemove(id);
        event.stopPropagation();
    }
}

function dataExportCollapse() {
    $("export_data_wrap").style.opacity = "0";
}

function dataExport() {
    myStorage.getDataAll(dataExportCallback, function(error) {
        messageShow("error", error);
    }, 0, !1);
}

function dataExportCallback(storage) {
    var i, today = new Date(), ddate = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate(), exportDataType = $.nm("export_data_type");
    for (i = 0; i < exportDataType.length; i++) if (exportDataType[i].checked) {
        exportDataType = exportDataType[i].value;
        break;
    }
    var matchType, data = '<?xml version="1.0" encoding="UTF-8"?>\n<data extensionName="Block Yourself from Analytics" extensionVersion="' + $.extensionVersion + '" date="' + ddate + '" format="1.0" browser="' + $.browserSlug + '">';
    data += "\n<websites>";
    for (i = 0; i < websiteExceptions.length; i++) {
        matchType = "m" === websiteExceptions[i].type ? "domain" : "domainWildcard";
        data += '<website domain="' + websiteExceptions[i].website + '" action="block" matchType="' + matchType + '" />';
    }
    data += "</websites>";
    if ("all" === exportDataType) {
        data += "\n<settings>";
        var value, settingIds = [ "showPopupMenuClose", "showSuggestions" ], settingIdsMap = {
            showPopupMenuClose: "popup_menu_close",
            showSuggestions: "show_suggestions"
        };
        for (i = 0; i < settingIds.length; i++) {
            value = storage[settingIds[i]] ? storage[settingIds[i]] : $(settingIds[i]).checked;
            data += '<config name="' + settingIdsMap[settingIds[i]] + '" value="' + value + '" />';
        }
        data += "</settings>";
    }
    data += "\n</data>";
    $("export_data").value = data;
    $("export_data_wrap").style.opacity = "1";
}

function dataImport() {
    $("import_status").textContent = "Starting import...";
    var message = "", parser = new DOMParser(), data = $("import_data").value.trim();
    if ("" !== data) {
        var dom = parser.parseFromString(data, "text/xml");
        if ("data" === dom.documentElement.nodeName) {
            var i, importDataType = $.nm("import_data_type");
            for (i = 0; i < importDataType.length; i++) if (importDataType[i].checked) {
                importDataType = importDataType[i].value;
                break;
            }
            if ("all" === importDataType) {
                var settingName, settingsFound = 0, settings = dom.querySelectorAll("settings > config"), settingIdsMap = {
                    popup_menu_close: "showPopupMenuClose",
                    show_suggestions: "showSuggestions"
                };
                for (i = 0; i < settings.length; i++) if (void 0 !== settingIdsMap[settingName = settings[i].getAttribute("name")]) {
                    settingsFound++;
                    $(settingIdsMap[settingName]).checked = "true" === settings[i].getAttribute("value");
                }
                message += settingsFound ? "Settings import finished. \n" : "No settings for import. \n";
            }
            var logSuccess = 0, logTotal = 0, websites = dom.querySelectorAll("websites > website");
            for (i = 0; i < websites.length; i++) if (websites[i].hasAttribute("domain")) {
                logTotal++;
                listAdd(websites[i].getAttribute("domain"), !1, !0) && logSuccess++;
            }
            0 === websites.length ? message += "No websites for import" : message += "Websites import finished, " + logSuccess + " websites added out of total " + logTotal + " websites";
            $("import_status").textContent = message;
            makeTable();
            mouseoverSuggestbox = !1;
            suggestboxHide();
            optionsChange();
        } else $("import_status").textContent = "ERROR: Unable to parse XML data, please check if your XML data is valid.";
    } else $("import_status").textContent = "ERROR: Data field is empty.";
}

function optionsLoad(storage) {
    websiteExceptions = $.options.getObject(storage.websiteList, []);
    makeTable();
    $.options.loadCheckbox(storage, "websiteRegex");
    $.options.loadCheckbox(storage, "showPopupMenuClose");
    $.options.loadCheckbox(storage, "showSuggestions");
    !1 !== storage.showSuggestions && chrome.tabs.query({
        windowType: "normal"
    }, function(tabs) {
        var i, tab;
        websiteSuggestions = [];
        for (i = 0; i < tabs.length; i++) if (0 === (tab = tabs[i]).url.indexOf("http")) {
            for (var tabUrl = $.domainFromURL(tab.url), found = !1, k = 0; k < websiteSuggestions.length; k++) if (websiteSuggestions[k] === tabUrl) {
                found = !0;
                break;
            }
            found || websiteSuggestions.push(tabUrl);
        }
    });
}

function optionsSave(doClose) {
    var storage = {};
    storage.websiteList = websiteExceptions;
    $.options.saveCheckbox(storage, "showPopupMenuClose");
    $.options.saveCheckbox(storage, "showSuggestions");
    $.storage.set(myStorage.__storageType, storage, function() {
        doClose && $.closeSelf();
        $("cmd_save").disabled = !0;
        $("cmd_apply").disabled = !0;
    }, function(error) {
        messageShow("error", error);
    });
}

function optionsChange() {
    $("cmd_save").disabled = !1;
    $("cmd_apply").disabled = !1;
}

function tabSwitch(event) {
    var element = event.target;
    if ("LI" === element.tagName) {
        event.stopPropagation();
        for (var els = document.getElementsByClassName("tab-selected"), i = els.length - 1; 0 <= i; i--) els[i].classList.remove("tab-selected");
        element.className = "tab-selected";
        $(element.id + "c").classList.add("tab-selected");
    }
}

function suggestboxShow() {
    function websiteInList(website) {
        for (var i = 0; i < websiteExceptions.length; i++) if ("m" === websiteExceptions[i].type) {
            if (website === websiteExceptions[i].website) return 1;
        } else if ("w" === websiteExceptions[i].type) {
            if (website.match(websiteExceptions[i].regex)) return 1;
        } else if (website.match(websiteExceptions[i].website)) return 1;
    }
    if (websiteSuggestions) {
        $.empty(suggestbox);
        var i = 0;
        for (i = 0; i < websiteSuggestions.length; i++) if (!websiteInList(websiteSuggestions[i])) {
            var lid = document.createElement("li");
            lid.textContent = websiteSuggestions[i];
            suggestbox.appendChild(lid);
        }
        0 !== i && (suggestboxContainer.style.display = "block");
    }
}

function suggestboxHide() {
    mouseoverSuggestbox || (suggestboxContainer.style.display = "none");
}

function suggestboxOnKeypress(event) {
    var i, li, found, key = event.which ? event.which : event.keyCode;
    if (38 === key) {
        li = suggestbox.getElementsByTagName("li");
        found = !1;
        for (i = 0; i < li.length; i++) if ("selected" === li[i].className) {
            li[i--].className = "";
            0 <= i && (li[i].className = "selected");
            found = !0;
            break;
        }
        !found && 0 < li.length && (li[li.length - 1].className = "selected");
        event.preventDefault();
        return !1;
    }
    if (40 === key) {
        if (suggestbox.children && "block" !== suggestboxContainer.style.display) suggestboxShow(); else {
            li = suggestbox.getElementsByTagName("li");
            found = !1;
            for (i = 0; i < li.length; i++) if ("selected" === li[i].className) {
                li[i++].className = "";
                i < li.length && (li[i].className = "selected");
                found = !0;
                break;
            }
            !found && 0 < li.length && (li[0].className = "selected");
        }
        event.preventDefault();
        return !1;
    }
    if (13 === key) {
        for (i = (li = suggestbox.getElementsByClassName("selected")).length - 1; 0 <= i; i--) {
            websiteUrl.value = li[i].innerText;
            mouseoverSuggestbox = !1;
            suggestboxHide();
            li[i].className = "";
            event.preventDefault();
            return !1;
        }
        websiteAdd();
    }
    return !0;
}

function suggestboxLiClick(event) {
    var element = event.target;
    if ("LI" === element.tagName) {
        event.stopPropagation();
        websiteUrl.value = element.innerText;
        mouseoverSuggestbox = !1;
        suggestboxHide();
        $("website_url_add").focus();
    }
}

function suggestboxLiMouseOver(event) {
    var element = event.target;
    if ("LI" === element.tagName) {
        for (var lis = element.parentElement.getElementsByClassName("selected"), i = lis.length - 1; 0 <= i; i--) lis[i].className = "";
        element.className = "selected";
    }
}

function suggestboxLiMouseOut(event) {
    var element = event.target;
    "LI" === element.tagName && (element.className = "");
}

function messageShow(messageType, message) {
    var alert = $("alert");
    $("alert-message").textContent = message;
    alert.className = "alert alert-" + messageType;
    "error" === messageType && window.console.error(message);
}

function messageHide() {
    $("alert").className = "alert alert-none";
}

window.addEventListener("DOMContentLoaded", function() {
    if ($.isBrowserSupported) {
        websiteUrl = $("website_url");
        suggestboxContainer = $("suggestbox_cont");
        suggestbox = $("suggestbox");
        $("tab_nav").addEventListener("click", tabSwitch, !1);
        $("opcije").addEventListener("change", optionsChange, !1);
        $("opcije").addEventListener("submit", function() {
            event.preventDefault();
            return !1;
        }, !1);
        websiteUrl.addEventListener("focus", suggestboxShow, !1);
        websiteUrl.addEventListener("blur", suggestboxHide, !1);
        websiteUrl.addEventListener("keydown", suggestboxOnKeypress, !1);
        $("websiteRegex").addEventListener("change", function() {
            $.storage.set(myStorage.__storageType, {
                websiteRegex: this.checked
            }, null, function(error) {
                messageShow("error", error);
            });
        }, !1);
        suggestboxContainer.addEventListener("mouseover", function() {
            mouseoverSuggestbox = !0;
        }, !1);
        suggestboxContainer.addEventListener("mouseout", function() {
            mouseoverSuggestbox = !1;
        }, !1);
        suggestbox.addEventListener("click", suggestboxLiClick, !1);
        suggestbox.addEventListener("mouseover", suggestboxLiMouseOver, !1);
        suggestbox.addEventListener("mouseout", suggestboxLiMouseOut, !1);
        $("website_url_add").addEventListener("click", websiteAdd, !1);
        $("exception_list_body").addEventListener("click", exceptionListBodyClick, !1);
        $("cmd_import").addEventListener("click", dataImport, !1);
        $("cmd_export").addEventListener("click", dataExport, !1);
        $("export_website_list").addEventListener("change", dataExportCollapse, !1);
        $("export_all").addEventListener("change", dataExportCollapse, !1);
        $("cmd_save").addEventListener("click", function() {
            optionsSave(!0);
        }, !1);
        $("cmd_apply").addEventListener("click", function() {
            optionsSave(!1);
        }, !1);
        $("cmd_close").addEventListener("click", function() {
            $.closeSelf();
        }, !1);
        $("tab_contact").href = "https://dev.tekin.cn/contactus.htmlus.html?referrer-ver=Block-Yourself-from-Analytics-v" + $.extensionVersion + "-on-" + $.browserSlug;
        $("alert-close").addEventListener("click", messageHide, !1);
        myStorage.getDataAll(optionsLoad, function(error) {
            messageShow("error", error);
        }, 0, !1);
        "options-hide extension-error" === document.body.className && (document.body.className = "");
    } else document.body.className = "options-hide extension-support";
}, !1);